package com.huluobo.a2308douyindemo.videos

import android.animation.ObjectAnimator
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.view.animation.BounceInterpolator
import android.view.animation.LinearInterpolator
import android.widget.EditText
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2308douyindemo.R
import com.huluobo.a2308douyindemo.adapter.CommentAdapter
import com.huluobo.a2308douyindemo.adapter.ItemType
import com.huluobo.a2308douyindemo.adapter.MultiVideoAdapter
import com.huluobo.a2308douyindemo.adapter.VideosAdapter
import com.huluobo.a2308douyindemo.bean.CollectBean
import com.huluobo.a2308douyindemo.bean.CommentBean
import com.huluobo.a2308douyindemo.bean.LikeVideoBean
import com.huluobo.a2308douyindemo.bean.ReplyBean
import com.huluobo.a2308douyindemo.bean.VideoBean
import com.huluobo.a2308douyindemo.databinding.FragmentVideosBinding
import com.huluobo.a2308douyindemo.live.LiveActivity
import com.huluobo.a2308douyindemo.mvvm.BaseFragment
import com.huluobo.a2308douyindemo.net.Const
import com.huluobo.a2308douyindemo.utils.MySp
import com.huluobo.a2308douyindemo.utils.MyToast
import com.huluobo.a2308douyindemo.utils.Utils.toTime
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.umeng.socialize.ShareAction
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb

class VideosFragment : BaseFragment<FragmentVideosBinding, VideoViewModel>() {
    private lateinit var videosAdapter: MultiVideoAdapter
    private val commentAdapter = CommentAdapter()
    private lateinit var player: StandardGSYVideoPlayer
    private val collectVideoIds = mutableListOf<Int>()

    //存放已点赞的视频
    private var likedVideosIds = mutableSetOf<Int>()

    //识别当前展示的item的下标
    private var currentPosition = 0

    //识别当前点击点赞或者回复的评论的下标
    private var currentCommentPosition = 0
    override fun initData() {
        //获取全部视频数据源
        vm.getVideos(1, 10)

//        //获取已点赞的数据源
//        vm.getLikeVideos("0", MySp.getInt(Const.PARAM_USER_ID))

        vm.getVideosSuccess.observe(this) {
//            it.data.forEach { videoBean ->
//                //如果视频的id在点赞集合中,证明当前视频已经被点赞
//                videoBean.isLiked = videoBean.id in likedVideosIds
//            }

            //由于要使用多布局,但是数据源中没有type的类型来区分,所以来给item的type赋值,用于区分多布局
            it.data.apply {
                repeat(this.size) { position ->
                    val type = when (position % 3) {
                        1 -> ItemType.TYPE_VIDEO
                        2 -> ItemType.TYPE_FULL
                        else -> ItemType.TYPE_LIVE
                    }
                    this[position].type = type
                }
            }
            //清空adapter中的数据源
            videosAdapter.data.clear()
            //添加数据源
            videosAdapter.data.addAll(it.data)
            //刷新适配器
            videosAdapter.notifyDataSetChanged()
        }

        vm.likeVideoSuccess.observe(this) {
//            ToastUtils.showLong(it.msg)
//            //点赞成功,切换爱心
//            (videosAdapter.getViewByPosition(
//                currentPosition,
//                R.id.item_videos_like_iv
//            ) as ImageView).setImageResource(R.drawable.ic_xihuanred)
//            //修改数据源中的是否被点赞为true
//            videosAdapter.data[currentPosition].isLiked = true
        }

        vm.unLikeVIdeoSuccess.observe(this) {
            ToastUtils.showLong(it.msg)
            //点赞成功,切换爱心
            (videosAdapter.getViewByPosition(
                currentPosition,
                R.id.item_videos_like_iv
            ) as ImageView).setImageResource(R.drawable.ic_xihuan)
            //修改数据源中的是否被点赞为true
            videosAdapter.data[currentPosition].isLiked = false
        }
//
//        vm.getLikeVideosSuccess.observe(this) {
//            //提取顶赞视频的id到一个set中
//            likedVideosIds = it.data.map { it.id }.toMutableSet()
//        }

        //评论列表的成功
        vm.getCommentSuccess.observe(this) {
            commentAdapter.data.clear()
            commentAdapter.data.addAll(it.data)
            commentAdapter.notifyDataSetChanged()
        }

        //发布评论的成功
        vm.sendCommentSuccess.observe(this) {
            //修改下标的位置为0,从index为0的位置添加最新的数据
            commentAdapter.data.add(0, it.data)
            commentAdapter.notifyDataSetChanged()
            //清空评论输入框
            (videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_et) as EditText).text.clear()
        }

        //评论点赞的成功
        vm.commentLikeSuccess.observe(this) {
            ToastUtils.showLong("点赞成功")
            (commentAdapter.getViewByPosition(
                currentCommentPosition,
                R.id.item_comment_like_iv
            ) as ImageView).setImageResource(R.drawable.ic_xihuanred)
        }

        //回复评论成功
        vm.replyCommentSuccess.observe(this) {
            //隐藏回复布局
            val commentReplyCl = commentAdapter.getViewByPosition(currentCommentPosition, R.id.item_comment_reply_cl)
            commentReplyCl!!.visibility = View.GONE
            //追加评论adapter中的回复的adapter中的数据源
            commentAdapter.replyAdapter.data.add(0, it.data)
            commentAdapter.replyAdapter.notifyDataSetChanged()
        }

        vm.focusedSuccess.observe(this) {
            if (it.data) {
                val addImage = videosAdapter.getViewByPosition(
                    currentPosition,
                    R.id.item_videos_add_iv
                ) as ImageView
                addImage.setImageResource(R.drawable.baseline_check_24)
                val alpha = ObjectAnimator.ofFloat(addImage, "alpha", 1f, 0f)
                alpha.duration = 1000
                alpha.start()
            }
        }

        //取消关注成功
        vm.unFocusSuccess.observe(this) {
            if (it.data) {
                val addImage = videosAdapter.getViewByPosition(
                    currentPosition,
                    R.id.item_videos_add_iv
                ) as ImageView
                addImage.alpha = 1f
                addImage.setImageResource(R.drawable.ic_add)
            }
        }

        //收藏成功
        vm.collectVideoSuccess.observe(this) {
            MyToast.showLong("收藏成功")
            val imageView = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_collect_iv) as ImageView
            imageView.setImageResource(R.drawable.ic_shoucangyellow)
        }

        vm.collectVideoNetSuccess.observe(this) {
//            MyToast.showLong("收藏成功")
//            val imageView = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_collect_iv) as ImageView
//            imageView.setImageResource(R.drawable.ic_shoucangyellow)
        }

        vm.queryLikeVideoSuccess.observe(this) {
            if (it != null) {
                if (it.id == videosAdapter.data[currentPosition].id) {
                    (videosAdapter.getViewByPosition(
                        currentPosition,
                        R.id.item_videos_like_iv
                    ) as ImageView).setImageResource(R.drawable.ic_xihuanred)
                    videosAdapter.data[currentPosition].isLiked = true
                }
            }
        }

        vm.likeVideoDbSuccess.observe(this) {
            ToastUtils.showLong("点赞成功")
            //点赞成功,切换爱心
            (videosAdapter.getViewByPosition(
                currentPosition,
                R.id.item_videos_like_iv
            ) as ImageView).setImageResource(R.drawable.ic_xihuanred)
            //修改数据源中的是否被点赞为true
            videosAdapter.data[currentPosition].isLiked = true
        }

        vm.deleteLikeVideoSuccess.observe(this) {
            ToastUtils.showLong("取消点赞成功")
            //点赞成功,切换爱心
            (videosAdapter.getViewByPosition(
                currentPosition,
                R.id.item_videos_like_iv
            ) as ImageView).setImageResource(R.drawable.ic_xihuan)
            //修改数据源中的是否被点赞为true
            videosAdapter.data[currentPosition].isLiked = false
        }

        vm.queryAllCollect(MySp.getInt(Const.PARAM_USER_ID), "0")
        vm.queryAllCollectSuccess.observe(this) {
            //查询到已收藏的所有视频,需要去查询当前展示的视频是否在已收藏视频中
            it.data.forEach { videoBean ->
                collectVideoIds.add(videoBean.id)
            }
        }
    }

    override fun initView() {
        val linearLayoutManager = LinearLayoutManager(requireContext())
        binding.videosRv.layoutManager = linearLayoutManager
        videosAdapter = MultiVideoAdapter()
        binding.videosRv.adapter = videosAdapter

        //页面辅助器
//        val pagerSnapHelper = PagerSnapHelper()
//        pagerSnapHelper.attachToRecyclerView(binding.videosRv)

        PagerSnapHelper().attachToRecyclerView(binding.videosRv)

        //RecyclerView添加滚动监听器
        binding.videosRv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            //获取RecyclerView的滚动后
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //通过linearManager获取正在显示的item的下标,来给当前下标赋值
                currentPosition = linearLayoutManager.findFirstVisibleItemPosition()
                //通过adapter获取当前下标的播放器
                player = (videosAdapter.getViewByPosition(
                    currentPosition,
                    R.id.item_videos_player
                ) as StandardGSYVideoPlayer)
                //自动播放
//                player.startPlayLogic()
                vm.queryLikeVideo(videosAdapter.data[currentPosition].id)
                val isCollect = videosAdapter.data[currentPosition].id in collectVideoIds
                videosAdapter.data[currentPosition].isCollect = isCollect
                if (isCollect) {
                    (videosAdapter.getViewByPosition(
                        currentPosition,
                        R.id.item_videos_collect_iv
                    ) as ImageView).setImageResource(R.drawable.ic_shoucangyellow)
                }
            }
        })

        //要想给adapter中的图标添加点击事件,必须要先声明该id可以点击
        videosAdapter.addChildClickViewIds(
            R.id.item_videos_like_iv,
            R.id.item_videos_comment_iv,
            R.id.item_videos_close_iv,
            R.id.item_videos_send_iv,
            R.id.item_videos_add_iv,
            R.id.item_videos_header_iv,
            R.id.item_videos_share_iv,
            R.id.item_videos_collect_iv,
            R.id.item_videos_live_cl,
            R.id.item_videos_full_cl
        )

        //设置adapter中的点击事件
        videosAdapter.setOnItemChildClickListener { adapter, view, position ->
            //获取adapter当中的bean
            val videoBean = videosAdapter.data[position]
            when (view.id) {
                R.id.item_videos_like_iv -> likeVideo(videoBean)
                R.id.item_videos_comment_iv -> openComment(videoBean)
                R.id.item_videos_close_iv -> closeComment()
                R.id.item_videos_send_iv -> sendComment(videoBean)
                R.id.item_videos_add_iv -> focusUser(videoBean)
                R.id.item_videos_header_iv -> unFocusUser(videoBean)
                R.id.item_videos_share_iv -> shareVideo(videoBean)
                R.id.item_videos_collect_iv -> collectVideo(videoBean)
                R.id.item_videos_live_cl -> toLive(videoBean)
                R.id.item_videos_full_cl -> fullScreen()
            }
        }

        //控制评论中列表的点击事件
        commentAdapter.addChildClickViewIds(
            R.id.item_comment_like_iv,
            R.id.item_comment_reply_tv,
            R.id.item_reply_tv
        )
        commentAdapter.setOnItemChildClickListener { adapter, view, position ->
            val commentBean = commentAdapter.data[position]
            currentCommentPosition = position
            when (view.id) {
                R.id.item_comment_like_iv -> commentLike(commentBean)
                R.id.item_comment_reply_tv -> showMore(commentBean)
                R.id.item_reply_tv -> replyComment(commentBean)
            }
        }
    }

    //全屏播放
    private fun fullScreen() {
        //允许屏幕自动翻转
        player.isRotateViewAuto = true
        //设置全屏播放 1上下文 2动作条(播放暂停) 3 状态条(播放进度)
        player.startWindowFullscreen(requireContext(), false, false)
    }

    //跳转直播间
    private fun toLive(videoBean: VideoBean) {
        //通过intent的形式传递对象
//        val bundle = Bundle()
//        bundle.putSerializable(Const.KEY_VIDEO, videoBean)
//        startAct(LiveActivity::class.java, bundle)
        //通过sp的形式传递对象
        val json = Gson().toJson(videoBean)
        MySp.putString(Const.KEY_VIDEO, json)
        startAct(LiveActivity::class.java)
    }

    // 收藏视频
    private fun collectVideo(videoBean: VideoBean) {
        vm.collectVideo(videoBean)
        val collectBean = CollectBean(
            System.currentTimeMillis().toTime(),
            0,
            videoBean.item_id.toLong(),
            0,
            MySp.getInt(Const.PARAM_USER_ID),
            "aaabbb"
        )
        vm.collectVideoNet(collectBean)
    }

    private fun shareVideo(videoBean: VideoBean) {
        //添加缩略图
        val umImage = UMImage(requireContext(), videoBean.videomainimag)
        //设置缩放比例
        umImage.compressStyle = UMImage.CompressStyle.SCALE

        //友盟分享的网页
        val umWeb = UMWeb(videoBean.videopath)
        //分享标题
        umWeb.title = videoBean.title
        //分享缩略图
        umImage.setThumb(umImage)
        umWeb.description = videoBean.description

        //打开分享动作条
        ShareAction(requireActivity())
            //设置显示的分享图标
            .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN)
            //添加分享媒体
            .withMedia(umWeb)
            .open()
    }

    //取消关注
    private fun unFocusUser(videoBean: VideoBean) {
        vm.unFocusUser(MySp.getInt(Const.PARAM_USER_ID), videoBean.userid)
    }

    //关注
    private fun focusUser(videoBean: VideoBean) {
        vm.focusedUser(MySp.getInt(Const.PARAM_USER_ID), videoBean.userid)
    }

    //回复评论
    private fun replyComment(commentBean: CommentBean) {
        //展示回复评论布局
        val commentReplyCl = commentAdapter.getViewByPosition(currentCommentPosition, R.id.item_comment_reply_cl)
        commentReplyCl!!.visibility = View.VISIBLE
        //如果展示更多tv不为空,隐藏掉
        val showMoreTv = commentAdapter.getViewByPosition(currentCommentPosition, R.id.item_comment_reply_tv)
        if (showMoreTv != null) {
            showMoreTv.visibility = View.GONE
        }
        //获取回复按钮
        val replyBtn = commentAdapter.getViewByPosition(currentCommentPosition, R.id.item_comment_reply_btn)
        replyBtn!!.setOnClickListener {
            //获取回复内容
            val content =
                (commentAdapter.getViewByPosition(
                    currentCommentPosition,
                    R.id.item_comment_reply_et
                ) as EditText).text.toString()
            if (content.isNotEmpty()) {
                //如果回复内容不为空,发起回复的网络请求
                val replyBean = ReplyBean(
                    0,
                    commentBean.id,
                    content,
                    System.currentTimeMillis().toTime(),
                    0,
                    MySp.get(Const.PARAM_USERNAME),
                    0,
                    MySp.getInt(Const.PARAM_USER_ID),
                    ""
                )
                vm.replyComment(replyBean)
            } else {
//                MyToast(requireContext(), "回复内容不能为空")
            }
        }
    }

    //展示更多评论方法
    private fun showMore(commentBean: CommentBean) {
        val commentRelyRv =
            commentAdapter.getViewByPosition(currentCommentPosition, R.id.item_comment_reply_rv) as RecyclerView
        commentRelyRv.visibility = View.VISIBLE
        commentAdapter.getViewByPosition(currentCommentPosition, R.id.item_comment_reply_tv)!!.visibility =
            View.GONE
    }

    //评论点赞
    private fun commentLike(commentBean: CommentBean) {
        vm.commentLike(commentBean.id)
    }

    //发送评论
    private fun sendComment(videoBean: VideoBean) {
        val contentEt = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_et) as EditText
        var content = ""
        //获取评论输入框,判断评论内容不为空时猜可以发送评论
        if (contentEt.text.isNotEmpty()) {
            content = contentEt.text.toString()
            //评论bean赋值,等待上传
            val commentBean = CommentBean(
                0,
                content,
                System.currentTimeMillis().toTime(),
                0,
                0,
                videoBean.item_id,
                MySp.get(Const.PARAM_USERNAME),
                null,
                0,
                MySp.getInt(Const.PARAM_USER_ID),
                ""
            )
            //触发网络请求
            vm.sendComment(commentBean)
        } else {
            contentEt.error = "评论内容不能为空"
        }

    }

    //关闭评论列表
    private fun closeComment() {
        val commentLayout = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll)
        if (commentLayout != null) {
            val animOut = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_out)
            animOut.duration = 500
            //插值器,改变动画的运行速率或效果
            animOut.interpolator = LinearInterpolator()
            commentLayout.startAnimation(animOut)

            animOut.setAnimationListener(object : AnimationListener {
                override fun onAnimationStart(animation: Animation?) {
                }

                override fun onAnimationEnd(animation: Animation?) {
                    //动画结束时,再让评论布局隐藏掉
                    commentLayout.visibility = View.GONE
                    binding.videosRv.setIntercept(true)
                }

                override fun onAnimationRepeat(animation: Animation?) {
                }
            })
        }
    }

    //打开评论列表
    private fun openComment(videoBean: VideoBean) {
        //打开评论列表,拦截掉最外层的RecyclerView事件,让事件无法传递到最外层,只在评论RecyclerView中触发
        binding.videosRv.setIntercept(false)
        //获取评论布局
        val commentLayout = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll)
        if (commentLayout != null) {
            commentLayout.visibility = View.VISIBLE
            //加载评论数据源
            vm.getComments(0, videoBean.item_id)
            val animIn = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_in)
            animIn.duration = 500
            //插值器,改变动画的运行速率或效果,弹球插值器
            animIn.interpolator = BounceInterpolator()
            commentLayout.startAnimation(animIn)

            //初始化评论列表布局
            val commentRv =
                videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_rv) as RecyclerView
            commentRv.layoutManager = LinearLayoutManager(requireContext())
            commentRv.adapter = commentAdapter
        }
    }

    //点赞或者取消点赞方法
    private fun likeVideo(videoBean: VideoBean) {
        if (videoBean.isLiked) {
//            val map = mapOf(
//                Const.PARAM_C_TIME to System.currentTimeMillis().toTime(),
//                Const.PARAM_ID to 0,
//                Const.PARAM_ITEM_CODE to videoBean.item_id,
//                Const.PARAM_SOURCE_FLAG to 0,
//                Const.PARAM_USER_ID to MySp.getInt(Const.PARAM_USER_ID),
//                Const.PARAM_VERIFY_CODE to "aaabbb"
//            )
//            vm.unLikeVideo(map)
            val likeVideoBean = LikeVideoBean(videoBean.id)
            vm.unLikeVideoDb(likeVideoBean)
        } else {
            //触发点赞
            //封装map,触发网络请求
//            val map = mapOf(
//                Const.PARAM_C_TIME to System.currentTimeMillis().toTime(),
//                Const.PARAM_ID to 0,
//                Const.PARAM_ITEM_CODE to videoBean.item_id,
//                Const.PARAM_SOURCE_FLAG to 0,
//                Const.PARAM_USER_ID to MySp.getInt(Const.PARAM_USER_ID),
//                Const.PARAM_VERIFY_CODE to "aaabbb"
//            )
//            vm.likeVideo(map)
            val likeVideoBean = LikeVideoBean(videoBean.id)
            vm.likeVideoDb(likeVideoBean)
        }
    }
}